package com.wortox.getPrice;

import com.wortox.common.GetFruitPrice;
import com.wortox.pojo.Fruit;
import com.wortox.setPrice.FruitPrice;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class SumPrice1 implements SumPrice {

    @Override
    public Integer getPrice(Map<String, Integer> fruitMap) {
        //获得水果的价格
        List<Fruit> fruitPrice = FruitPrice.getInstance().getFruitPrice();

        Integer sum = 0;
        Iterator<Map.Entry<String, Integer>> iterator = fruitMap.entrySet().iterator();
        //循环遍历获得传入的水果和斤数
        while (iterator.hasNext()) {
            Map.Entry<String, Integer> next = iterator.next();
            String fruit = next.getKey();
            //水果斤数为负，抛出异常,没有找到该水果，抛出异常
            Integer weight = null;
            Integer price = null;
            try {
                weight = next.getValue();
                if(weight < 0) {
                    throw new IllegalArgumentException();
                }

                price = GetFruitPrice.findPrice(fruit);
                if(price < 0) {
                    throw new NullPointerException();
                }
            } catch (IllegalArgumentException e) {
                System.out.println("商品数量错误");
                weight = 0;
                price = 0;
            } catch (NullPointerException e) {
                System.out.println("商品不存在");
                weight = 0;
                price = 0;
            }

            //获得总价
            AtomicInteger integer = new AtomicInteger(sum);
            sum = integer.addAndGet(weight * price);
        }

        return sum /100;
    }
}
